//
//  FunctionsExample.swift
//  SwiftCode
//
//  Created by yuhus on 2023/10/10.
//

import Foundation

/// 函数
class FunctionsExample: ListViewController {
  override func getItemCount() -> Int {
    data.count
  }
  
  override func getItem(_ indexPath: IndexPath) -> Item {
    data[indexPath.row]
  }
  
  private lazy var data: [Item] = [
    .init(title: "输入输出参数", description: "交换参数值", action: testSwapTwoInts),
    .init(title: "函数类型", description: "函数类型作为返回类型", action: testChooseStepFunction),
    .init(title: "嵌套函数", description: "对外界不可见", action: nestedFunctions),
  ]
}

private func testSwapTwoInts() {
  var someInt = 3
  var anotherInt = 107
  
  print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
  swapTwoInts(&someInt, &anotherInt)
  print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
  // 打印“someInt is now 107, and anotherInt is now 3”
}

private func swapTwoInts(_ a: inout Int, _ b: inout Int) {
  let temporaryA = a
  a = b
  b = temporaryA
}

private func stepForward(_ input: Int) -> Int {
  return input + 1
}

private func stepBackward(_ input: Int) -> Int {
  return input - 1
}

private func chooseStepFunction(backward: Bool) -> (Int) -> Int {
  return backward ? stepBackward : stepForward
}

private func testChooseStepFunction() {
  var currentValue = 3
  let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
  // moveNearerToZero 现在指向 stepBackward() 函数。
  
  print("Counting to zero:")
  // Counting to zero:
  while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
  }
  print("zero!")
  // 3...
  // 2...
  // 1...
  // zero!
}

private func nestedFunctions() {
  func chooseStepFunction(backward: Bool) -> (Int) -> Int {
    func stepForward(input: Int) -> Int { return input + 1 }
    func stepBackward(input: Int) -> Int { return input - 1 }
    return backward ? stepBackward : stepForward
  }
  var currentValue = -4
  let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
  // moveNearerToZero now refers to the nested stepForward() function
  while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
  }
  print("zero!")
  // -4...
  // -3...
  // -2...
  // -1...
  // zero!
}
